import React, { useState, useEffect } from 'react';
import { 
  Layout, 
  Menu, 
  Card, 
  Button, 
  Input, 
  Tabs, 
  Modal, 
  Form,
  Select,
  Tag,
  Table,
  Space,
  Typography,
  message,
  Row,
  Col
} from 'antd';
import { 
  AppstoreOutlined, 
  SendOutlined, 
  SaveOutlined, 
  HistoryOutlined,
  SearchOutlined,
  EditOutlined,
  DeleteOutlined,
  CalendarOutlined,
  ClockCircleOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined
} from '@ant-design/icons';

const { Header, Content, Sider } = Layout;
const { TabPane } = Tabs;
const { Title, Text } = Typography;

const App = () => {
  const [activeTab, setActiveTab] = useState('create');
  const [templates, setTemplates] = useState([]);
  const [history, setHistory] = useState([]);
  const [currentCard, setCurrentCard] = useState('');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalContent, setModalContent] = useState('');
  const [searchText, setSearchText] = useState('');
  
  // 模板类型预设
  const templateTypes = [
    { key: 'text', name: '文本卡片', description: '简单的文本内容卡片' },
    { key: 'markdown', name: 'Markdown卡片', description: '支持Markdown格式的卡片' },
    { key: 'action_card', name: '操作卡片', description: '包含按钮操作的卡片' },
    { key: 'feed_card', name: '信息卡片', description: '多条信息流展示' },
    { key: 'link', name: '图文卡片', description: '带图片的图文混排卡片' },
    { key: 'single_action_card', name: '单按钮卡片', description: '只有一个操作按钮的卡片' },
    { key: 'oa_message', name: 'OA消息', description: '适合审批、公告等场景' }
  ];

  // 加载模板数据
  useEffect(() => {
    fetchTemplates();
    fetchHistory();
  }, []);

  const fetchTemplates = async () => {
    try {
      // 这里应该调用实际的API端点
      // const response = await fetch('/api/templates');
      // const data = await response.json();
      // setTemplates(data.templates || []);
      
      // 模拟数据
      setTemplates([
        { name: '通知模板', content: { msgtype: 'text', text: { content: '这是一条通知' } }, tags: ['通知', '系统'], category: '通知类' },
        { name: '告警模板', content: { msgtype: 'markdown', markdown: { title: '告警', text: '# 告警信息\n系统出现异常' } }, tags: ['告警', '紧急'], category: '告警类' },
        { name: '审批模板', content: { msgtype: 'actionCard', actionCard: { title: '审批', text: '有新的审批请求', btns: [{ title: '同意', actionURL: '#' }] } }, tags: ['审批', '工作流'], category: '审批类' }
      ]);
    } catch (error) {
      message.error('加载模板失败');
    }
  };

  const fetchHistory = async () => {
    try {
      // 这里应该调用实际的API端点
      // const response = await fetch('/api/send-history');
      // const data = await response.json();
      // setHistory(data.history || []);
      
      // 模拟数据
      setHistory([
        { id: 1, msgtype: 'text', timestamp: '2023-10-01 10:00:00', result: { errmsg: null } },
        { id: 2, msgtype: 'markdown', timestamp: '2023-10-01 11:00:00', result: { errmsg: '发送失败' } },
        { id: 3, msgtype: 'actionCard', timestamp: '2023-10-01 12:00:00', result: { errmsg: null } }
      ]);
    } catch (error) {
      message.error('加载历史记录失败');
    }
  };

  const handleTemplateSelect = (templateType) => {
    // 根据模板类型设置默认JSON内容
    const defaultTemplates = {
      text: {
        msgtype: "text",
        text: { content: "这是一条纯文本消息" }
      },
      link: {
        msgtype: "link", 
        link: {
          text: "这是一条图文消息的描述",
          title: "图文消息标题", 
          picUrl: "",
          messageUrl: "https://www.example.com"
        }
      },
      action_card: {
        msgtype: "actionCard",
        actionCard: {
          title: "操作卡片标题",
          text: "![image](https://www.dingtalk.com/logo.png)\n### 操作卡片\n您有一项待处理任务\n- 任务1: 内容描述\n- 任务2: 内容描述",
          btnOrientation: "0",
          btns: [
            {
              title: "确认操作",
              actionURL: "https://www.dingtalk.com"
            },
            {
              title: "取消操作", 
              actionURL: "https://www.dingtalk.com"
            }
          ]
        }
      },
      markdown: {
        msgtype: "markdown",
        markdown: {
          title: "Markdown卡片",
          text: "# 标题\n\n这是一段**加粗**的文本和*斜体*文本。\n\n- 列表项1\n- 列表项2\n\n[链接文本](https://www.example.com)"
        }
      },
      feed_card: {
        msgtype: "feedCard",
        feedCard: {
          links: [
            {
              title: "时代的火车向前开1",
              messageURL: "https://www.example.com",
              picURL: "https://www.dingtalk.com/logo.png"
            },
            {
              title: "时代的火车向前开2",
              messageURL: "https://www.example.com",
              picURL: "https://www.dingtalk.com/logo.png"
            }
          ]
        }
      },
      single_action_card: {
        msgtype: "actionCard",
        actionCard: {
          title: "进度提醒",
          text: "任务“项目周报”截至今天，请及时完成",
          hideAvatar: "0",
          btnOrientation: "0",
          singleTitle: "查看任务",
          singleURL: "https://www.example.com"
        }
      },
      oa_message: {
        msgtype: "oa",
        oa: {
          message_url: "https://www.example.com",
          head: {
            bgcolor: "FFBBBBBB",
            text: "审批通知"
          },
          body: {
            title: "请假申请",
            form: [
              {"key": "申请人：", "value": "张三"},
              {"key": "请假类型：", "value": "年假"},
              {"key": "请假时间：", "value": "2023-01-01 至 2023-01-03"}
            ],
            rich: {
              "num": "3",
              "unit": "天"
            },
            content: "请假事由：回家探亲",
            image: "https://www.dingtalk.com/logo.png",
            file_count: "1",
            author: "行政部"
          }
        }
      }
    };
    
    setCurrentCard(JSON.stringify(defaultTemplates[templateType], null, 2));
  };

  const handleSendCard = async () => {
    try {
      // 实际发送卡片的API调用
      // const response = await fetch('/api/send', {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: currentCard
      // });
      // 
      // if (response.ok) {
      //   message.success('卡片发送成功');
      //   fetchHistory(); // 刷新历史记录
      // } else {
      //   message.error('发送失败');
      // }
      
      // 模拟发送
      message.success('卡片发送成功（模拟）');
    } catch (error) {
      message.error('发送失败');
    }
  };

  const handleSaveTemplate = async (values) => {
    try {
      // 实际保存模板的API调用
      // const response = await fetch(`/api/templates/${values.name}`, {
      //   method: 'POST',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({
      //     content: JSON.parse(currentCard),
      //     category: values.category,
      //     tags: values.tags ? values.tags.split(',') : []
      //   })
      // });
      // 
      // if (response.ok) {
      //   message.success('模板保存成功');
      //   setIsModalVisible(false);
      //   fetchTemplates(); // 刷新模板列表
      // } else {
      //   message.error('保存失败');
      // }
      
      // 模拟保存
      message.success('模板保存成功（模拟）');
      setIsModalVisible(false);
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleSearch = (value) => {
    setSearchText(value);
    // 实际搜索的API调用
  };

  const columns = [
    {
      title: '消息类型',
      dataIndex: 'msgtype',
      key: 'msgtype',
    },
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (text) => new Date(text).toLocaleString()
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={record.result?.errmsg ? 'error' : 'success'}>
          {record.result?.errmsg ? '失败' : '成功'}
        </Tag>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            onClick={() => {
              setModalContent(JSON.stringify(record.content, null, 2));
              setIsModalVisible(true);
            }}
          >
            查看
          </Button>
        </Space>
      ),
    },
  ];

  const templateColumns = [
    { title: '模板名称', dataIndex: 'name', key: 'name' },
    { title: '类型', dataIndex: 'content.msgtype', key: 'msgtype' },
    { 
      title: '标签', 
      key: 'tags',
      render: (_, record) => (
        <Space wrap>
          {record.tags?.map(tag => <Tag key={tag}>{tag}</Tag>)}
        </Space>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link"
            onClick={() => {
              setCurrentCard(JSON.stringify(record.content, null, 2));
              message.success('模板已加载');
            }}
          >
            加载
          </Button>
          <Button 
            type="link" 
            danger
            icon={<DeleteOutlined />}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Header className="header" style={{ background: '#fff', padding: 0 }}>
        <div style={{ padding: '0 24px', fontSize: '18px', fontWeight: 'bold', color: 'white' }}>
          钉钉卡片发送器
        </div>
      </Header>
      
      <Layout>
        <Sider width={200} style={{ background: '#fff' }}>
          <Menu
            mode="inline"
            defaultSelectedKeys={['create']}
            style={{ height: '100%', borderRight: 0 }}
            onSelect={({ key }) => setActiveTab(key)}
          >
            <Menu.Item key="create" icon={<EditOutlined />}>
              创建卡片
            </Menu.Item>
            <Menu.Item key="history" icon={<HistoryOutlined />}>
              发送历史
            </Menu.Item>
            <Menu.Item key="templates" icon={<AppstoreOutlined />}>
              模板管理
            </Menu.Item>
          </Menu>
        </Sider>
        
        <Layout style={{ padding: '0 24px 24px' }}>
          <Content style={{ padding: 24, margin: 0, minHeight: 280, background: '#fff' }}>
            <Tabs activeKey={activeTab} onChange={setActiveTab}>
              <TabPane tab="创建卡片" key="create">
                <Row gutter={[16, 16]}>
                  <Col span={24}>
                    <Title level={4}>选择卡片样式</Title>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 16 }}>
                      {templateTypes.map(type => (
                        <Card 
                          key={type.key}
                          title={type.name}
                          style={{ width: 200, cursor: 'pointer' }}
                          onClick={() => handleTemplateSelect(type.key)}
                          hoverable
                        >
                          <Text type="secondary">{type.description}</Text>
                        </Card>
                      ))}
                    </div>
                  </Col>
                  
                  <Col span={24}>
                    <Title level={4}>卡片内容 (JSON)</Title>
                    <Input.TextArea
                      rows={15}
                      value={currentCard}
                      onChange={(e) => setCurrentCard(e.target.value)}
                      placeholder="请在此输入钉钉卡片的JSON格式内容"
                    />
                  </Col>
                  
                  <Col span={24}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <Space>
                        <Button 
                          type="primary" 
                          icon={<SaveOutlined />}
                          onClick={() => setIsModalVisible(true)}
                        >
                          保存模板
                        </Button>
                        <Button 
                          type="primary" 
                          icon={<SendOutlined />}
                          onClick={handleSendCard}
                        >
                          发送卡片
                        </Button>
                      </Space>
                      
                      <Space>
                        <Button>预览</Button>
                        <Button>清空</Button>
                      </Space>
                    </div>
                  </Col>
                </Row>
              </TabPane>
              
              <TabPane tab="发送历史" key="history">
                <div style={{ marginBottom: 16 }}>
                  <Input.Search 
                    placeholder="搜索历史记录..." 
                    onSearch={handleSearch}
                    style={{ width: 300 }}
                  />
                </div>
                
                <Table 
                  columns={columns} 
                  dataSource={history} 
                  rowKey="id"
                  pagination={{ pageSize: 10 }}
                />
              </TabPane>
              
              <TabPane tab="模板管理" key="templates">
                <div style={{ marginBottom: 16 }}>
                  <Input.Search 
                    placeholder="搜索模板..." 
                    onSearch={handleSearch}
                    style={{ width: 300 }}
                  />
                </div>
                
                <Table 
                  columns={templateColumns} 
                  dataSource={templates} 
                  rowKey="name"
                  pagination={{ pageSize: 10 }}
                />
              </TabPane>
            </Tabs>
          </Content>
        </Layout>
      </Layout>
      
      {/* 保存模板模态框 */}
      <Modal
        title="保存模板"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          layout="vertical"
          onFinish={handleSaveTemplate}
        >
          <Form.Item
            name="name"
            label="模板名称"
            rules={[{ required: true, message: '请输入模板名称' }]}
          >
            <Input placeholder="输入模板名称" />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
          >
            <Select placeholder="选择分类">
              <Select.Option value="通知类">通知类</Select.Option>
              <Select.Option value="告警类">告警类</Select.Option>
              <Select.Option value="审批类">审批类</Select.Option>
              <Select.Option value="默认分类">默认分类</Select.Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="tags"
            label="标签"
          >
            <Input placeholder="输入标签，用逗号分隔" />
          </Form.Item>
          
          <Form.Item>
            <Button type="primary" htmlType="submit" block>
              保存模板
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default App;